<!--新闻增加界面-->

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:include="include/admin/adminHeader::html('新增新闻')">
</head>
<!--个人样式-->
<link href="css/index.css" rel="stylesheet">

<!--以下富文本所需-->
<link href="http://twitter.github.com/bootstrap/assets/js/google-code-prettify/prettify.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.no-icons.min.css"
      rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-responsive.min.css"
      rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css" rel="stylesheet">
<!--键盘事件-->
<script src="js/jquery.hotkeys.js"></script>
<script src="js/bootstrap-wysiwyg.js"></script>
<!--以上富文本所需-->


<!--数据校验插件静态资源文件-->
<script src="js/bootstrapValidator.min.js"></script>
<link href="css/bootstrapValidator.min.css" rel="stylesheet">


<style>
    div.container div.row div {
        margin: 5px 0px;
        text-align: center;
    }
</style>

<body>
<div>
    <div id="workingArea">
        <div class="container">
            <div class="row">
                <!--栅栏布局12列开始-->
                <div class="col-md-12">
                    <div th:replace="include/admin/adminNavigator::html"></div>
                </div>


                <!--面包屑导航-->
                <div class="col-md-12" style="text-align: left">
                    <ol class="breadcrumb">
                        <li><a href="/home">个人中心</a></li>
                        <li>新闻发布</li>
                    </ol>
                </div>


                <!--栅栏布局3列-->

                <div th:replace="include/admin/adminLeftMenu::html"></div>

                <!--栅栏布局9列开始-->

                <div class="col-md-9 col-sm-12 col-xs-12 " >

                    <form class=" form-horizontal" role="form">

                        <div class="col-sm-12 col-xs-12 form-group">
                            <label class=" control-label">文章标题：</label>
                            <div class="col-md-6  col-xs-7">
                                <input name="note_title" class="form-control" v-model="bean.note_title"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-12">
                                <div style="height: 30px;"></div>
                                <!--这里加上是为了让提示信息显示 不然会被遮挡-->
                                <div class="btn-toolbar" data-role="editor-toolbar" data-target="#editor">
                                    <div class="btn-group">
                                        <a class="btn dropdown-toggle" data-toggle="dropdown" title="Font"><i
                                                class="icon-font"></i><b class="caret"></b></a>
                                        <ul class="dropdown-menu"></ul>
                                    </div>
                                    <div class="btn-group">
                                        <a class="btn dropdown-toggle" data-toggle="dropdown" title="Font Size"><i
                                                class="icon-text-height"></i> <b class="caret"></b></a>
                                        <ul class="dropdown-menu">
                                            <li><a data-edit="fontSize 5"><font size="5">Huge</font></a></li>
                                            <li><a data-edit="fontSize 3"><font size="3">Normal</font></a></li>
                                            <li><a data-edit="fontSize 1"><font size="1">Small</font></a></li>
                                        </ul>
                                    </div>
                                    <div class="btn-group">
                                        <a class="btn" data-edit="bold" title="Bold (Ctrl/Cmd+B)"><i
                                                class="icon-bold"></i></a> <!--加粗-->
                                        <a class="btn" data-edit="italic" title="Italic (Ctrl/Cmd+I)"><i
                                                class="icon-italic"></i></a><!-- 斜体-->
                                        <a class="btn" data-edit="strikethrough" title="Strikethrough"><i
                                                class="icon-strikethrough"></i></a><!-- 删除线-->
                                        <a class="btn" data-edit="underline" title="Underline (Ctrl/Cmd+U)"><i
                                                class="icon-underline"></i></a><!-- 下划线-->
                                    </div>
                                    <div class="btn-group">
                                        <a class="btn" data-edit="insertunorderedlist" title="Bullet list"><i
                                                class="icon-list-ul"></i></a><!-- 加点-->
                                        <a class="btn" data-edit="insertorderedlist" title="Number list"><i
                                                class="icon-list-ol"></i></a><!-- 数字排序-->
                                        <a class="btn" data-edit="outdent" title="Reduce indent (Shift+Tab)"><i
                                                class="icon-indent-left"></i></a><!-- 减少缩进-->
                                        <a class="btn" data-edit="indent" title="Indent (Tab)"><i
                                                class="icon-indent-right"></i></a><!--增加缩进-->
                                    </div>
                                    <div class="btn-group">
                                        <a class="btn" data-edit="justifyleft" title="Align Left (Ctrl/Cmd+L)"><i
                                                class="icon-align-left"></i></a><!--左对齐-->
                                        <a class="btn" data-edit="justifycenter" title="Center (Ctrl/Cmd+E)"><i
                                                class="icon-align-center"></i></a><!--居中-->
                                        <a class="btn" data-edit="justifyright" title="Align Right (Ctrl/Cmd+R)"><i
                                                class="icon-align-right"></i></a><!--右对齐-->
                                        <a class="btn" data-edit="justifyfull" title="Justify (Ctrl/Cmd+J)"><i
                                                class="icon-align-justify"></i></a><!--垂直对齐-->
                                    </div>
                                    <div class="btn-group">
                                        <a class="btn dropdown-toggle" data-toggle="dropdown" title="Hyperlink"><i
                                                class="icon-link"></i></a><!-- 链接-->
                                        <div class="dropdown-menu input-append">
                                            <input class="span2" placeholder="URL" type="text" data-edit="createLink"/>
                                            <button class="btn" type="button">Add</button>
                                        </div>
                                        <a class="btn" data-edit="unlink" title="Remove Hyperlink"><i
                                                class="icon-cut"></i></a>
                                    </div>
                                    <div class="btn-group">
                                        <a class="btn" title="Insert picture (or just drag & drop)" id="pictureBtn"><i
                                                class="icon-picture"></i></a>
                                        <input id="descripitionImg" type="file" data-role="magic-overlay"
                                               data-target="#pictureBtn"
                                               data-edit="insertImage"/>
                                    </div>
                                    <div class="btn-group">
                                        <a class="btn" data-edit="undo" title="Undo (Ctrl/Cmd+Z)"><i
                                                class="icon-undo"></i></a><!--撤销-->
                                        <a class="btn" data-edit="redo" title="Redo (Ctrl/Cmd+Y)"><i
                                                class="icon-repeat"></i></a><!--恢复-->
                                    </div>
                                    <input type="text" data-edit="inserttext" id="voiceBtn" x-webkit-speech="">
                                </div>
                                <div style="height: 50px;"></div>
                                <div name="note" id="editor" style="text-align: left ;height: 300px">

                                </div>

                            </div>
                        </div>
                        <div class=" form-group">
                            <label class="col-md-offset-2 col-md-4 col-sm-4 col-xs-offset-3  col-xs-4 control-label">文章类型：</label>
                            <div class="col-md-3 col-sm-3 col-xs-3">
                                <select name="note_type" class="form-control" v-model="bean.note_type">
                                    <option v-for="type in types" :value="type">
                                        {{type.name}}
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-11">
                                <button class="btn btn-primary" type="submit" @click="testAdd">增加</button>
                            </div>

                        </div>
                    </form>
                    <!--栅栏布局9列结束-->
                </div>
            </div>
        </div>

    </div>
</div>

<!--前后端交互-->
<script>
    $(function () {
        /*文档加载开始*/
        var data4Vue = {
            uri: "new",
            bean: {
                id: 0, user_write: {id: 0}, refer_time: "", note_type: {id: 0}, note_title: "", note: ""
                , image_url: "", video_url: "", user_auditor: "", auditor_time: "", state: "未审核"
            },
            types: [],
            image: "",
            video: ""
        };

        //ViewModel
        var vue = new Vue({
            el: '#workingArea',
            data: data4Vue,
            mounted: function () { //mounted　表示这个 Vue 对象加载成功了
                this.getNewType();
                this.getUser();
            },
            methods: {
                getUser: function () {
//                    vue.bean.user_write=[[${session.user}]];
                    this.bean.user_write.id = parseInt([[${session.user.id}]]);
//                    alert(this.bean.user_write.id);
                },
                getNewType: function () {
                    var url = "type";
                    axios.get(url).then(function (response) {
                        vue.types = response.data.data.content;
                        //                        console.log(vue.types);
                    })
                },

                add: function () {
                    console.log(this.bean.note);
                    var url = this.uri;
                    var formData = new FormData();
                    formData.append("user_write", this.bean.user_write.id);
//                    formData.append("refer_time", this.bean.refer_time);
                    formData.append("note_title", this.bean.note_title);
                    formData.append("note", this.bean.note);
                    formData.append("note_type", this.bean.note_type.id);
                    formData.append("user_auditor", this.bean.user_auditor);
//                    formData.append("auditor_time", this.bean.auditor_time);
                    formData.append("state", this.bean.state);
//                    formData.append("image", this.image);
//                    formData.append("video", this.video);
                    formData.append("files", this.image);
                    formData.append("files", this.video);
                    axios.post(url, formData, {headers: {'Content-Type': 'multipart/form-data'}})
                        .then(function () {
                            alert("增加成功");
                        });

                },
                getImage: function (event) {
                    this.image = event.target.files[0];
                },
                getVideo: function (event) {
                    this.video = event.target.files[0];
                },
                logout: function () {
                    var url = "logout";
                    axios.post(url).then(function (response) {
                        console.log(response.data);
                        if (response.data.code == 0) location.href = "fore_login";
                    });
                },
                /*测试富文本编辑器内容获取*/
                testAdd: function () {
                    /*bootstrap提交验证*/
                    var validator = $('form').data('bootstrapValidator').validate();
                    if (!validator.isValid()) {
                        //没有通过校验
                        alert(0);
                        return;
                    } else {
                        //通过校验，可进行提交等操作

                    }
                    var index = uploadFiles.length;
                    uploadImgs(index);
                },
            }
        });


        /*富文本编辑器*/


        // 照片路径保存
        var uploadFiles = [];
        // 监听选取照片的按钮<input type="file" data-role="magic-overlay" data-target="#pictureBtn" data-edit="insertImage" />，
        // 把每次选取的照片文件放入数组中
        $("#descripitionImg").change(function () {
            $.each(this.files, function (index, fileObj) {
                uploadFiles.push(fileObj);
//                alert("1");
            });
        });

        /*转码图片*/
        var readFileIntoDataUrl = function (fileInfo) {
            var loader = $.Deferred(),  //jq延迟对象
                fReader = new FileReader();
            fReader.onload = function (e) {
                loader.resolve(e.target.result);
            };
            fReader.onerror = loader.reject; //拒绝
            fReader.onprogress = loader.notify;
            fReader.readAsDataURL(fileInfo); //转码图片
            return loader.promise();  //返回promise
        };

        function uploadImgs(index) {
            // 使用FormData对象上传文件
            // 这里上传使用递归上传，上传一个再次调用函数本身，再次上传，知道全部上传完成
            var formData = new FormData();
            if (0 >= index) {
                // 再次上传文本编辑器里的内容
                vue.bean.note = $("#editor").html();
                vue.add();
            } else {
                //console.log('执行照片提交。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。');
                index -= 1;
                formData.append("editorImage", uploadFiles[index]);
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "addImg", true);
                xhr.send(formData);
                xhr.onload = function (data) {
                    // 判断图片是否存在
                    var imgTag = [];
                    readFileIntoDataUrl(uploadFiles[index]).done(function (dataUrl) {
                        imgTag = $("#editor").find("img[src='" + dataUrl + "']");
                        if (imgTag.length > 0) {
                            // 图片存在, 上传当前文件.
                            // uploadImage方法为你的上传图片方法.
                            var url = JSON.parse(data.currentTarget.response).data;
                            imgTag.attr("src", url);
                            alert(url);
                            // 重新调用函数
                            uploadImgs(index);
                        }
                    });
                }
            }
        }

        function initToolbarBootstrapBindings() {
            var fonts = ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
                    'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
                    'Times New Roman', 'Verdana'],
                fontTarget = $('[title=Font]').siblings('.dropdown-menu');
            $.each(fonts, function (idx, fontName) {
                fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>'));
            });
            $('a[title]').tooltip({container: 'body'});
            $('.dropdown-menu input').click(function () {
                return false;
            })
                .change(function () {
                    $(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle');
                })
                .keydown('esc', function () {
                    this.value = '';
                    $(this).change();
                });

            $('[data-role=magic-overlay]').each(function () {
                var overlay = $(this), target = $(overlay.data('target'));
                overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight());
            });
            $('#voiceBtn').hide();
            if ("onwebkitspeechchange" in document.createElement("input")) {
                var editorOffset = $('#editor').offset();
                $('#voiceBtn').css('position', 'absolute').offset({
                    top: editorOffset.top,
                    left: editorOffset.left + $('#editor').innerWidth() - 35
                });
            } else {
                $('#voiceBtn').hide();
            }
        };

        function showErrorAlert(reason, detail) {
            var msg = '';
            if (reason === 'unsupported-file-type') {
                msg = "Unsupported format " + detail;
            } else {
                console.log("error uploading file", reason, detail);
            }
            $('<div class="alert"> <button type="button" class="close" data-dismiss="alert">×</button>' +
                '<strong>File upload error</strong> ' + msg + ' </div>').prependTo('#alerts');
        };
        initToolbarBootstrapBindings();
        $('#editor').wysiwyg({fileUploadError: showErrorAlert});
    });
</script>

<!--富文本编辑器-->
<script>

</script>

<!--bootstrapvalidator数据校验-->
<!--由于select和editor div没办法校验 这里暂不使用表单数据校验-->
<script>
    $(function () {
        $('form').bootstrapValidator({

            message: 'This value is not valid',
//            excluded: [':disabled'],
            feedbackIcons: {
//                valid: 'glyphicon glyphicon-ok',
//                invalid: 'glyphicon glyphicon-remove',
//                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                note_title: {
                    message: '用户信息输入有误',
                    validators: {
                        notEmpty: {
                            message: '请输入一个文章标题'
                        }
                    }
                },
                note_type: {
                    message: '角色验证失败',
                    validators: {
                        notEmpty: {
                            message: '请选择一个文章类型'
                        },
                        callback: {
//                            message: '必须选择一个文章类型',
                            callback: function (value, validator) {
                                if (value == -1) {
                                    return false;
                                } else {
                                    return true;
                                }

                            }
                        }
                    }
                },
            }
        });
    });
</script>
</body>
</html>
